package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.annotation.RequriedPermission;
import cn.wolfcode.wms.domain.Permission;
import cn.wolfcode.wms.mapper.PermissionMapper;
import cn.wolfcode.wms.query.QueryObject;
import cn.wolfcode.wms.service.IPermissionService;
import cn.wolfcode.wms.util.PermissionUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private ApplicationContext cxt;
    public void save(Permission permission) {
        permissionMapper.insert(permission);
    }

    public void delete(Long id) {
        permissionMapper.deleteByPrimaryKey(id);
    }

    public List<Permission> list() {
        return permissionMapper.selectAll();
    }

    public PageInfo<Permission> query(QueryObject qo) {
//        调用分页包
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Permission> list = permissionMapper.queryForList(qo);
        return new PageInfo<Permission>(list);
    }
//权限加载
    public void reload() {
//        从列表中查询所有权限表达式
        List<String> exps = permissionMapper.selectExpression();
//        从容器中获取贴有标签的类
        Map<String, Object> map = cxt.getBeansWithAnnotation(Controller.class);
        Collection<Object> ctls = map.values();
        Method[] methods = ctls.getClass().getDeclaredMethods();
        for (Method method : methods) {
//            获取贴有标签的方法;
            RequriedPermission annotation = method.getAnnotation(RequriedPermission.class);
            if (annotation != null){
//                通过方法获取该方法的权限表达式
                String expression = PermissionUtil.selectexpressionByMethod(method);
                if (exps.contains(expression)){
                    continue;
                }
//                将通过方法获取的权限表达式,列表中没有,即存入
                Permission p = new Permission();
                p.setExpression(expression);
                p.setName(annotation.value());
                permissionMapper.insert(p);
            }
        }

    }

}
